package com.filyar.htyd.config.interceptor;

import com.filyar.htyd.common.ExceptionEnum;
import com.filyar.htyd.exception.ServiceException;
import com.filyar.htyd.utils.IpUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author Feiliya
 * @date: 2024/3/23 19:11
 * @email: root@filyar.com
 */
public class IpBlacklistInterceptor implements HandlerInterceptor {
    private final static String BLOCK_PREFIX = "block:";

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String ip = IpUtils.getIpAddress(request);
        Boolean hasKey = stringRedisTemplate.hasKey(BLOCK_PREFIX + ip);
        if (Boolean.TRUE.equals(hasKey)){
            throw new ServiceException(ExceptionEnum.BLOCK_IP.getCode(), ExceptionEnum.BLOCK_IP.getMsg()+":"+ip,false);
        }
        return true;
    }
}
